package com.edgar.postgresql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @Author EdgarLQS
 * @Date 2022/08/31/10/08
 **/
public class PgClient {

    private Connection c = null;
    private Statement stmt = null;
    private ResultSet rs = null;

    void init() {

       try {
           Class.forName("org.postgresql.Driver");
           c = DriverManager
                   .getConnection("jdbc:postgresql://localhost:5432/pgtest",
                           "sde", "admin");
       } catch (Exception e) {
           e.printStackTrace();
           System.err.println(e.getClass().getName()+": "+e.getMessage());
           System.exit(0);
       }
       System.out.println("Opened database successfully");

    }

    public ResultSet ExcuteSql(String str) {

        try {
            stmt = c.createStatement();
            rs = stmt.executeQuery( str );
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            System.exit(0);
        }
        return rs;
    }

    public String GetString(ResultSet rs, String fieldName) {
        String str = "";
        try {
            int row = rs.getRow();
            if (row > 1) {
                while ( rs.next() ) {
                    str = rs.getString(fieldName);
                    System.out.println(fieldName + " = " + str);
                }
            }
        } catch ( Exception e ) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            System.exit(0);
        }
        return str;
    }

    void close() {
        try {
            rs.close();
            stmt.close();
            c.close();
        } catch (Exception e) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
        }
        System.out.println("Close database successfully");
    }

}
